
from fastapi import Form
from src.core.session import *
from src.entity.models import User, UpdateUser, CreateUser, BasicModel
from src.core.logconfig import log
from src.common.response import success_response, fail_response
from src.common.status import CLASS_STATUS
from src.utils.tools import get_cur_time
from src.common.base_router import BaseRouter
from src.common.base_service import BaseService


# 使用基础路由类创建路由
user = BaseRouter(
    entity=User,
    create_schema=CreateUser,
    update_schema=UpdateUser,
    prefix="/sys/user",
    tags=["User"]
).router

log = log.logger
sc = SQLCON

# 创建服务实例
user_service = BaseService(User)

def generate_idcard():
    # 获取最大编号，如果无，则从1开始
    # 前缀根据用户部门进行命名，此处需要去查询用户用户所属的部门，暂时默认为T
    s = 'T'
    _uid = sc.db_query_filter(User, select(User.id).order_by(User.id.desc()), single=True)
    if _uid is None:
        _uid = 0
    return s.upper() + str(int(_uid+1)).zfill(5)

async def query_all():
    return user_service.get_list()


async def query_one(id: int=Form()):
    return user_service.get_by_id(id)

async def create(name: str=Form(), username: str=Form(), password: str=Form(default='123456'), phone: str=Form(default=''), email: str=Form(default=''), state:int=Form(default=1)):
        
    # 创建新用户
    create_data = CreateUser(
        name=name,
        username=username,
        idcard=generate_idcard(),
        password=password,
        phone=phone,
        email=email,
        state=state,
        create_time=get_cur_time())
    
    # 调用服务层创建用户
    return user_service.create(create_data)

async def update(id:int=Form(), name:str=Form(), username=Form(), phone=Form(default=''), email: str=Form(default=""), state:int=Form(default=1)):
        
    # 更新数据
    update_data = UpdateUser(
        id=id,
        name=name,
        username=username,
        phone=phone,
        email=email,
        state=state,
        update_time=get_cur_time())
    
    # 调用服务层更新用户
    return user_service.update(update_data)

async def delete(data: BasicModel):
    # 更新数据为删除状态
    delete_data = UpdateUser(
        id=data.id,
        state=CLASS_STATUS["STATE_DELETED"],
        update_time=get_cur_time())
    # 调用服务层更新用户
    return user_service.update(delete_data)
